package com.yaohuan;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Enumeration;
import java.util.Map;
import java.util.UUID;
import java.util.function.BiConsumer;

/**
 * @author YaoHuan
 * @ClassName MyServlet
 * @Description servlet测试类  https://blog.51cto.com/zwbjava/1789880
 * https://blog.kalan.dev/2021-03-13-html-form-data
 * @Date 2022/11/22 14:28
 */
public class MyServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        ServletContext servletContext = getServletContext();
        Enumeration attributeNames = servletContext.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            Object key = attributeNames.nextElement();
            System.out.println(key+":"+servletContext.getAttribute((String) key));
        }
        System.out.println("Hello World!");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String contentType = req.getContentType();
        System.out.println("Content-Type:"+contentType);
        switch (contentType) {
            case "application/x-www-form-urlencoded":
                doPostForFormUrencoded(req, resp);
                break;
            case "application/json":
                try {
                    doPostForJSON(req, resp);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                break;
            case "application/xml":
                try {
                    doPostForJSON(req, resp);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                break;
//            case "application/x-www-form-urlencoded":
//                break;
        }
//        // 获取文件上传时的标记
//        String boundaryText = req.getContentType().substring(req.getContentType().indexOf("boundary=") + 9);
//        System.out.println(boundaryText);
//
//        ServletInputStream  in = null;
//
//        // 先以文本格式缓存文件
//        in = req.getInputStream();
//        File tmpFile = null, fileIO = null;
//        FileOutputStream fileout = null;
//
//        tmpFile = new File("D:\\project\\maven-demo\\test.txt");
//
//        if (tmpFile.exists()) {
//            tmpFile.createNewFile();
//        }
//
//        fileout = new FileOutputStream(tmpFile);
//
//        byte[] tmp_byte = new byte[1024];
//
//        int tmp = -1;
//
//        while ((tmp = in.read(tmp_byte)) > -1) {
//                fileout.write(tmp_byte, 0, tmp);
//        }
//
//       fileout.flush();
//
//         fileout.close();

    }

    /**
     *  x-www-form-urlencoded格式的post请求处理
    */
    private void doPostForFormUrencoded(HttpServletRequest req, HttpServletResponse resp) {
        Map<String,String[]> parameterMap = req.getParameterMap();
        parameterMap.forEach((parameter, value) -> {
            System.out.println("parameter:"+parameter+",value:"+value[0]);
        });
    }

    private void doPostForJSON(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //从前端获取输入字节流
        ServletInputStream requestInputStream = req.getInputStream();
        //将字节流转换为字符流,并设置字符编码为utf-8
        InputStreamReader ir = new InputStreamReader(requestInputStream,"utf-8");
        //使用字符缓冲流进行读取
        BufferedReader br = new BufferedReader(ir);
        //开始拼装json字符串
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null) {
            sb.append(line);
        }

        System.out.println(sb.toString());


    }
}
